import React,{Component} from "react";
import {Table, Select, Pagination, Button, Form, Input, Checkbox, Icon, Row, Col, message, Popconfirm} from "antd";
import {Link, withRouter} from "react-router-dom";
import '../../editor/ueditor.config.js';
import '../../editor/ueditor.all.js';
import '../../editor/lang/zh-cn/zh-cn.js';
import config from  '../../editor/my.config';
import ajax from '../../ajaxMethod.js';

import moment from "moment";


const container = "container";

class News extends Component{
    constructor(props){
        super(props);
        this.state = {
            UIstate:{
                nomalDisplay:"block",
                addDispaly:"none",
            },
            initialValue:{
                searchTitle:(()=>{
                    let condition =  sessionStorage.getItem("condition");
                    if(condition){
                        condition = JSON.parse(condition);
                        return condition.searchTitle;
                    }else{
                        return undefined;
                    }
                })(),
                searchAuthor:(()=>{
                    let condition =  sessionStorage.getItem("condition");
                    if(condition){
                        condition = JSON.parse(condition);
                        return condition.searchAuthor;
                    }else{
                        return undefined;
                    }
                })(),
            },
            data:[],
            ue: undefined,
            selectedRows:[],
        }
    }

    componentDidMount() { 
        let condition = sessionStorage.getItem("condition");
        if(condition){
            condition = JSON.parse(condition);
            if(Object.keys(condition).length){
                this.getList(condition);
            } else {
                this.getList();
                sessionStorage.setItem("condition", JSON.stringify({}));
            }
        }else{
            this.getList();
            sessionStorage.setItem("condition", JSON.stringify({}));
        }
        this.initEditor();
    }
    
    componentWillUnmount(){ 
        // sessionStorage.clear(); 
        UE.delEditor(container); 
    }

    getList = (condition) =>{
        let _this = this;
        ajax.getAjax("/interface/management/news/getList",condition, 
        res=>{
            if(res.data){
                _this.setState({data: res.data});
            }else{
                message.error("没有数据返回");
                condition.log("res",res);
            }
        },
        error=>{
            console.error(error);
        });
    }
    initEditor =()=> {
        //加载前先卸载。和绑定事件类似
        UE.delEditor(container);
        const ueEditor = UE.getEditor(container, config);
        const self = this;
        ueEditor.ready((ueditor) => {
            if (!ueditor) {
                // ueEditor.delEditor(container);
                self.initEditor();
            }
        })
        this.setState({ue: ueEditor});
    }
    addItem = (e) =>{
        let fileDom = document.getElementById("cover");
        let img = document.getElementById("preview");
        this.setState({UIstate:{nomalDisplay:"none", addDispaly:"block"}});
        this.props.form.resetFields();
        let ue = this.state.ue;
        //设置清空里面的内容
        fileDom.value = "";//清空图片
        img.removeAttribute("src");
        img.style.display = "none";
        if(ue){
            if(ue.hasContents()){
                ue.execCommand('cleardoc');
            }
        }
        this.props.form.resetFields();
    }
    onSearch = (e) =>{
        let values = this.props.form.getFieldsValue();
        let condition = {};
        if(values.searchTitle) condition.searchTitle = values.searchTitle;
        if(values.searchAuthor) condition.searchAuthor = values.searchAuthor;
        sessionStorage.setItem("condition", JSON.stringify(condition));
        this.getList(condition);
    }
    backClick = (e) =>{ this.setState({UIstate:{nomalDisplay:"block", addDispaly:"none"}}); }
    deleteAll = (e) =>{
        let selectedRows = this.state.selectedRows;
        let arr = [];
        //如果没有选中的提示没有选中的，有的话就将id包装为数组发一个请求
        if(selectedRows.length > 0){
            for(let i = 0; i < selectedRows.length; i++){
                arr.push(selectedRows[i].id);
            }
            //发送请求
            ajax.postAjax("/interface/management/news/delete",{"ids":arr}, res=>{
                message.success("删除成功");
                window.location.reload();
            },
            error=>{
                console.error(error);
            });
        }else{
            message.warning("没有选中的数据");
        }
    }
    //直接向后台请求删除，然后刷新页面
    deleteOne(id){
        let arr = [];
        arr.push(id);
        ajax.postAjax("/interface/management/news/delete",{"ids": arr}, res=>{
            message.success("删除成功");
            window.location.reload();
        },
        error=>{
            message.error("删除失败,请联系管理员");
            console.error(error);
        });
    }
    //获将id传过去，新的页面获取数据。
    getDetail(id){
        let path = { pathname:"/management/newsDetail", params: {id:id}, values: {id:id} };
        this.props.history.push(path);
    }
    
    imgPreview = (e) =>{
        //判断是否支持FileReader
        let reader;
        if (window.FileReader) {
            reader = new FileReader();
        } else {
            alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
            return;
        }
        //获取文件
        let fileDom = document.getElementById("cover");
        let file = fileDom.files[0];
        let imageType = /^image\//;
        //是否是图片
        if(file){
            if (!imageType.test(file.type)) {
                alert("请选择图片！");
                return;
            }
        }
        //读取完成
        reader.onload = function(e) {
            //获取图片dom
            let img = document.getElementById("preview");
            //图片路径设置为读取的图片
            if(img){
                img.src = e.target.result;
                img.style.display = "block";
                img.style.opacity = "1";
            }
        };
        //读取指定的 Blob 或 File 对象。读取操作完成的时候，readyState 会变成已完成DONE，并触发 loadend 事件，
        //同时 result 属性将包含一个data:URL格式的字符串（base64编码）以表示所读取文件的内容。
        reader.readAsDataURL(file);
    }
    
    //提交数据
    onSubmit = (e) =>{
        let values = this.props.form.getFieldsValue();
        let imgFile = document.getElementById("cover").files[0];
        let img = document.getElementById("preview");
        let fd = new FormData();
        let _this = this; 

        delete values.searchTitle;
        delete values.searchAuthor;
        delete values.cover;
        values.content = this.state.ue.getContent();
        values.contentName = (new Date()).getTime();
        console.log("imgFile",imgFile);
        if(imgFile){
            fd.append("cover", imgFile, imgFile.name || ('blob.' + imgFile.type.substr('image/'.length)));
            fd.append("values", JSON.stringify(values));

            if(img.getAttribute("src")){
                for(let item in values){
                    if(!item){
                        message.error("请输入所有内容");
                        return;
                    }
                }
                ajax.postBinaryAjax("/interface/management/news/newArticle",fd,function(res){
                    if(res.success){
                        message.success("提交成功");
                        _this.setState({ UIstate:{ nomalDisplay:"block", addDispaly:"none"} });
                        window.location.reload();
                    }else{
                        message.error("后台出错,暂时无法上传");
                    }
                });
            }else{
                message.error("请上传封面图片封面");
            }
        }else{
            message.error("请上传图片");
        }
        e.preventDefault();
    }

    render(){
        const state = this.state;
        const _this = this;
        const { getFieldProps } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
        };
        const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            width:300,
        },{
            title: '作者',
            dataIndex: 'author',
            key: 'author',
            width:200,
        },{
            title: '发布日期',
            dataIndex: 'date',
            key: 'date',
            width:200,
            sorter: (a, b) => a.date > b.date,
        }, {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width:100,
            sorter: (a, b) => {
                if(a.type > b.type)return 1;
                else return -1;
            },
        }, {
            title: '操作',
            key: 'operation',
            width:200,
            render: (text, record) => (
            <span>
                <a onClick={this.getDetail.bind(this, record.id)}>详情</a>
                <span> | </span>
                <Popconfirm title="确定要删除该条数据？" onConfirm={this.deleteOne.bind(this, record.id)}><a>删除</a></Popconfirm>
            </span>
            ),
        }];
        const rowSelection = {
            onChange(selectedRowKeys, selectedRows) {
              _this.setState({selectedRows:selectedRows});
            }
        };
        const data = (()=>{
            let arr = [];
            for(let i = 0; i < state.data.length; i++){
                arr.push({
                    key:i,
                    title: state.data[i].title,
                    author: state.data[i].author,
                    id: state.data[i]._id,
                    type: (()=>{
                        let type = "公告";
                        switch(state.data[i].type){
                            case 1: type = "机场";break;
                            case 2: type = "飞机";break;
                            case 3: type = "乘客";break;
                            default:;
                        }
                        return type;
                    })(),//文章类型，0：公告，1：机场，2：飞机，3：乘客
                    date:moment(state.data[i].date).format("YYYY/MM/DD"),
                });
            }
            return arr;
        })();
        
        return(
        <div className="news">
            <div className="nomal" style={{display: state.UIstate.nomalDisplay}}>
                <div className="contral">
                    <Form layout="inline" >
                        <Form.Item>
                            <Button onClick={this.addItem}>新增</Button>
                        </Form.Item>
                        <Form.Item>
                            <Popconfirm placement="bottom" title="确定删除所有选择数据？" onConfirm={this.deleteAll}>
                                <Button>删除选中</Button>
                            </Popconfirm>
                        </Form.Item>
                        <Form.Item label="文章标题">
                            <Input placeholder="文章标题" {...getFieldProps('searchTitle',{initialValue: this.state.initialValue.searchTitle})}></Input>
                        </Form.Item>
                        <Form.Item label="文章作者">
                            <Input placeholder="文章作者" {...getFieldProps('searchAuthor',{initialValue: this.state.initialValue.searchAuthor})}>
                        </Input></Form.Item>
                        <Form.Item>
                            <Button className="search" onClick={this.onSearch}>查询</Button>
                        </Form.Item>
                    </Form>
                </div>
                <Table rowSelection={rowSelection} columns={columns} dataSource={data} scroll={{ y: 400 }}
                    pagenation={
                        <Pagination
                            total={80}
                            showTotal={total => `共 ${total} 条`}
                            pageSize={20} defaultCurrent={1}
                        />
                    }
                ></Table>
            </div>
            <div className="add" style={{display: state.UIstate.addDispaly}}>
                <div className="contral">
                    <Button className="back" onClick={this.backClick}>返回</Button>
                </div>
                <Form onSubmit={this.onSubmit}>
                    <Form.Item label="封面" {...formItemLayout} >
                        <div className="img-box">
                            <div className="head-show">
                                <div className="cross"></div>
                                <div className="verti"></div>
                            </div>
                            <input type="file" className="head-src"
                                {...getFieldProps('cover', { rules: [{required: true, message:"请上传封面"}], onChange: this.imgPreview})}
                            />
                            <img id="preview" ></img>
                            <span className="tip">请上传图片，2m以下，尺寸：280px*120px</span>
                        </div>
                    </Form.Item>
                    <Form.Item label="标题" {...formItemLayout}>
                        <Input {...getFieldProps('title', { rules: [{required: true, message:"请输入标题"}]})}></Input>
                    </Form.Item>
                    <Form.Item label="作者" {...formItemLayout}>
                        <Input  {...getFieldProps('author', { rules: [{required: true, message:"请输入作者"}]})}></Input>
                    </Form.Item>
                    <Form.Item label="分类" {...formItemLayout} >
                        <Select {...getFieldProps('type',{rules:[{required: true}],initialValue: 0 })}>
                            <Select.Option value={0}>公告</Select.Option>
                            <Select.Option value={1}>机场</Select.Option>
                            <Select.Option value={2}>飞机</Select.Option>
                            <Select.Option value={3}>乘客 </Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item {...{
                        labelCol: {
                            xs: { span: 24 },
                            sm: { span: 12 },
                            //sm是表示从横坐标的8开始，24表示总共有24个
                        },
                        wrapperCol: {
                            xs: { span: 24 },
                            sm: { span: 18 },
                            //sm表示宽度
                        },
                    }}>
                        <Checkbox {...getFieldProps('top')}>置顶</Checkbox>
                    </Form.Item>
                    <Form.Item>
                        <p className="content-tip">*插入的视频只支持mkv、avi、rmvb、.wmv、mp4格式，大小不超过30m，图片不能超过2m</p>
                        <script id={container} name="content" type="text/plain"></script>
                    </Form.Item>
                    <Row>
                        <Button className="submit-btn" type="primary" htmlType="submit">发布</Button>
                    </Row>
                </Form>

            </div>
        </div>)
    }
}

export default withRouter(Form.create({})(News));